#coding:utf-8
#python BilibiliDanmu.py link account password

import requests
import re
import datetime
import sys  
  
#登录bilibili
def login(account, password):
    loginUrl = "https://passport.bilibili.com/ajax/miniLogin/login"
    loginData = {"userid":account,
                 "pwd":password,
                 "keep":"1",
                 "captcha":""}
    rq = requests.session()
    rp = rq.post(url=loginUrl,data=loginData)
    return rp.cookies

#获取av号
def getAvId(url):
    return url.replace(re.search(r"(.*?av)(.*?)",url).group(1),"").replace("/","")

#获取cid （弹幕文件ID）
def getDanmuId(url):
    return re.search(r"cid=(.*?)&aid=",requests.get(url=url).content).group(1)

#发送弹幕
def sendDanmu(danmuId,avid,msg,time,cookies):
    danmuUrl = "http://interface.bilibili.com/dmpost?cid="+danmuId+"&aid="+avid+"&pid=1"
    danmuData = {"date":datetime.datetime.now(),
                 "mode":"1",
                 "cid":danmuId,
                 "color":"16777215",
                 "message":msg,
                 "pool":"0",
                 "playTime":time,
                 "fontsize":"25"}
    rq = requests.post(url=danmuUrl,data = danmuData,cookies=cookies)
    if rq.content == '0' :
        print u'请稍后重新发送（哔哩哔哩系统要求间隔5秒）'
        print ''

url = sys.argv[1]
cookies =  login(sys.argv[2],sys.argv[3])
avid = getAvId(url)
danmuId = getDanmuId(url)
while 1:
    msg = raw_input("Msg :  ")
    sendDanmu(danmuId,avid,msg,"0",cookies)